﻿using Language.Resource;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Threading.Tasks;
using VisionCloud.Api.Common;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.Filters;
using VisionCloud.Service.Ms;

namespace VisionCloud.Api.Controllers.Ms
{
    /// <summary>
    /// 更新模块
    /// </summary>
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [SystemModule("更新模块")]
    [ApiVersion("1.0")]
    [Route("api/ms/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "更新模块")]
    public class MsUpdateController : ApiBaseController
    {
        /// <summary>
        /// 更新服务
        /// </summary>
        public MsUpdateService MsUpdateService { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<ControllerResource> localizer { get; set; }

        /// <summary>
        /// 查询最新版本
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> GetLastUpdate()
        {
            return await TryCatchAsync(MsUpdateService.GetLastUpdate());
        }

        /// <summary>
        /// 下载更新包
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult DownloadUpdate(JObject obj)
        {
            Guid updateId = obj.GetAndCheck<Guid>("UpdateId");
            var result = MsUpdateService.DownloadSingle(updateId);
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[result.Result.fileExt];
            return File(result.Result.fileStream, memi, Path.GetFileName(result.Result.fileName));
        }

        /// <summary>
        /// 上传更新压缩包
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Upload(IFormCollection request)
        {
            if (request.Files.Count > 0)
            {
                var version = request["version"];
                return await TryCatchAsync(MsUpdateService.UploadFile(version, request.Files[0]));
            }

            return ApiResult.Error(localizer["YB0007"].Value);//new ApiResult(AjaxCode.Error, localizer["YB0007"].Value);
        }
    }
}